#include "tcpInit.h"
#include <unistd.h>
#include "../../log/utils/error_utils.h"

#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <stdlib.h>

int tcp_server_init(const char *ip, const char *port)
{
    // 参数检查
    if (ip == NULL || port == NULL)
    {
        return SYSTEM_ERR_INVALID_ARGUMENT;
    }
    // 创建套接字
    int server_fd = socket(AF_INET, SOCK_STREAM, 0);
    // 错误检查
    if (server_fd < 0)
    {
        return SYSTEM_ERR_NETWORK_FAILURE;
    }
    // 设置socket选项：地址复用
    int opt = 1;
    setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    // 错误检查
    if (opt < 0)
    {
        close(server_fd);
        return SYSTEM_ERR_NETWORK_FAILURE;
    }
    // 绑定地址和端口
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(ip);
    server_addr.sin_port = htons(atoi(port));
    int bind_ret = bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    // 错误检查
    if (bind_ret < 0)
    {
        close(server_fd);
        return SYSTEM_ERR_NETWORK_FAILURE;
    }
    // 监听端口
    int listen_ret = listen(server_fd, 5);
    // 错误检查
    if (listen_ret < 0)
    {
        close(server_fd);
        return SYSTEM_ERR_NETWORK_FAILURE;
    }

    return server_fd;
}